package uk.ac.sanger.das.dasregistry.springrest.coordinates;

import java.util.Date;

import org.apache.log4j.Logger;
import org.biodas.jdas.schema.lastmodified.LASTMODIFIED;
import org.biodas.jdas.schema.registrycoordinates.DASCOORDINATESYSTEM;
import org.biodas.jdas.schema.servers.SERVERS;
import org.biodas.jdas.schema.sources.COORDINATES;
import org.biodas.jdas.schema.sources.SOURCES;



public class CoordinatesCache extends Thread implements Runnable, CoordinatesManager{
	 
	Date lastUpdate;//last time data was updated
	CoordinatesDao coordinatesDao;
	private DASCOORDINATESYSTEM coordinatesCache;
	private long pause=300005;
	
	Logger logger=Logger.getLogger(CoordinatesCache.class);

	public CoordinatesCache(CoordinatesDao coordinatesDao){
		this.coordinatesDao=coordinatesDao;
	}
	
	
	
	public void run( ) {
        for (;;) {
            
            try {
                Thread.sleep(10005);
                this.getAllCoordinates();
            } catch (InterruptedException ie) {
            	ie.printStackTrace();
                return;
            }
        }
    }



	@Override
	public DASCOORDINATESYSTEM getAllCoordinates() {
		java.util.Date lastMod = coordinatesDao.getLastModified();
		logger.debug("lastModified in coords cache="+lastMod);
		if (timeToUpdate(lastMod, lastUpdate, pause)) {
			refreshCache();
		}
		return coordinatesCache; 
	}



	private synchronized void refreshCache() {
		logger.warn("coordinates cache is refreshing from dao");
		coordinatesCache=coordinatesDao.getAllCoordinates();
		lastUpdate=new Date(System.currentTimeMillis());
	}


	public boolean timeToUpdate(Date lastMod, Date lastUpdate, long pause){
		if (coordinatesCache == null || lastUpdate==null){
			logger.warn("lastupdate or coordinates cache is null so we update");
			return true;
		}
		//logger.debug("lastmod="+lastMod.toString());
		//logger.debug("lastUpdate="+lastUpdate.toString());
		//logger.debug("pause seconds="+pause/1000);
		//if lastmodified is after last update we want to update, but we need a delay in cases of mirroring 
		//so we need to add a delay
		Date delay=null;
		if(lastUpdate!=null){
			delay=new Date(lastUpdate.getTime()+pause);
		}
		Date now=new Date(System.currentTimeMillis());
		if (now.after(delay)&&lastMod.after(lastUpdate)){
			logger.warn("-----------------------------need to update coordinates--------------------------");
			return true;
		}
		 return false;
	}
	
	@Override
	public synchronized DASCOORDINATESYSTEM add(DASCOORDINATESYSTEM coordinate)
			throws DasCoordinateNotRegisterableExcepton {
		coordinatesCache.getCOORDINATES().add(coordinate.getCOORDINATES().get(0));
		return null;
	}
}
